<template>
  <div>
    <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
      <el-row>
        <el-col class="singleDatePicker">
          <el-form-item prop="tenderName" label="投标项目" size="small">
            <el-autocomplete
              v-model="teamRow.tenderName"
              :fetch-suggestions="querySearchProject"
              @select="handleSelectProject"
              placeholder="请输入内容"
              style="width: 190px;"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item v-if="teamRow.teamName" label="所属团队" size="small">
            {{teamRow.teamName}}
          </el-form-item>
          <el-form-item prop="amount" label="保证金金额" size="small">
            <el-input type="number" v-model.number="teamRow.amount">
              <span slot="suffix">万元</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="datePay" label="打款时间" size="small">
            <el-date-picker
              v-model="teamRow.datePay"
              type="date"
              value-format="timestamp"
              placeholder="选择日期"
              style="width: 190px;"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="receiveCompany" label="打款单位" size="small">
            <el-select v-model="teamRow.receiveCompany" placeholder="请选择">
              <el-option
                v-for="item in global.billUnitList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="serviceFee" label="资金周转费" size="small">
            <el-input type="number" v-model.number="teamRow.serviceFee">
              <span slot="suffix">元</span>
            </el-input>
          </el-form-item>
          <el-form-item label="支出凭证" size="small">
            <input type="file" ref='payCertificate' @change="getFile($event)">
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
      <el-button size="small" @click="$emit('closeDialog')">取消</el-button>
    </div>
  </div>
</template>

<script>
  import {
    addTenderDeposit,
    deleteTenderDeposit,
    getTenderDepositList,
    selectTenderDeposit,
    selectTenderName,
    updateIsReturn,
    updateIsTransfer,
    updateTenderDeposit
  } from '@/api/tenderdeposit'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const datePay = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const receiveCompany = function(row, column) {
    if (row.receiveCompany) {
      let obj = {}
      obj = global.billUnitList.find((item) => {
        return item.value === row.receiveCompany // 筛选出匹配数据
      })
      return obj.label
    }
  }

  const dateReturn = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        if (time) {
          var date = new Date(time)
          return formatDate(date, 'yyyy-MM-dd')
        } else {
          return ''
        }
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const isReturn = {
    props: ['colConfig'],
    filters: {
      isReturn(type) {
        const returns = type ? '是' : '否'
        return returns
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | isReturn }}
      </span>
  </el-table-column>
  `
  }

  const payCertificate = {
    props: ['colConfig'],
    methods: {
      openVisible(label, src) {
        const msg = {
          label: label,
          src: src
        }
        this.$emit('openImgVisible', msg)
      }
    },
    filters: {},
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        <a v-if="scope.row[colConfig.prop]" @click="openVisible(colConfig.label,scope.row[colConfig.prop])">查看</a>
      </span>
  </el-table-column>
  `
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    props: ['outerVisible', 'balanceId'],
    data() {
      return {
        colConfigs: [
          { prop: 'tenderName', label: '投标项目名称', width: '350', fixed: true },
          { prop: 'teamName', label: '团队名称', width: '80' },
          { prop: 'amount', label: '保证金金额(万元)', width: '120' },
          { prop: 'returnPay', label: '退还金额(万元)', width: '100' },
          { prop: 'datePay', label: '打款时间', width: '100', component: datePay },
          { prop: 'receiveCompany', label: '打款单位', width: '100', formatter: receiveCompany },
          { prop: 'serviceFee', label: '资金周转费(元)', width: '100' },
          { prop: 'address', label: '详细地址', width: '150' },
          { prop: 'isReturn', label: '是否退还保证金', width: '120', component: isReturn },
          { prop: 'dateReturn', label: '退还时间', width: '100', component: dateReturn },
          { prop: 'totalServiceFee', label: '服务费(元)', width: '80' },
          { prop: 'payCertificate', label: '支出凭证', width: '80', component: payCertificate },
          { slot: 'opt' }
        ],
        searchForm: {
          provinceId: '',
          cityId: ''
        },
        searchFormList: {},
        costTypes: [],
        typeNames: [],
        listLoading: true,
        dialogTitle: '新增投标保证金支出',
        marginTitle: '',
        marginType: 1,
        dialogType: 1,
        teamRow: {},
        teamRowClear: {},
        margin: {},
        marginClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        marginVisible: false,
        pca: pca,
        rules: {
          tenderName: [
            { required: true, message: '请输入项目名称', trigger: 'change' }
          ],
          amount: [
            { required: true, message: '请输入保证金金额', trigger: 'change' }
          ],
          datePay: [
            { required: true, message: '请选择打款时间', trigger: 'change' }
          ],
          receiveCompany: [
            { required: true, message: '请选择打款单位', trigger: 'change' }
          ]
        },
        marginRules: {
          date: [
            { required: true, message: '请选择打入时间', trigger: 'change' }
          ]
        },
        visible: false,
        imgVisible: false,
        imgMsg: {},
        isReturnList: [
          { value: 1, label: '是' },
          { value: 0, label: '否' }
        ]
      }
    },
    created() {
      // this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      // this.fetchData()
    },
    computed: {
      global() {
        return global
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.searchFormList.amountType = 2
        this.listLoading = true
        getTenderDepositList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          console.log(this.tableData)
          this.listLoading = false
        })
      },
      provinceChange() {
        this.searchForm.cityId = ''
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 1
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
      },
      editTeam(depositId) {
        this.outerVisible = true
        this.dialogTitle = '修改投标保证金支出'
        this.dialogType = 0
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        const params = {
          depositId: depositId
        }
        selectTenderDeposit(params).then(response => {
          this.teamRow = response.responseBody
        })
      },
      editMargin(type, row) {
        if (this.$refs['margin']) {
          this.$refs['margin'].resetFields()
        }
        this.marginVisible = true
        this.marginType = type
        this.marginTitle = type === 1 ? '打入保证金' : '退还保证金'
        this.margin = JSON.parse(JSON.stringify(this.marginClear))
        this.margin.depositId = row.depositId
        this.margin.serviceFee = row.serviceFee
        this.margin.tenderId = row.tenderId
        this.margin.teamId = row.teamId
        this.margin.amount = row.amount
        this.margin.totalServiceFee = row.totalServiceFee
        this.margin.returnPay = Math.round((row.amount - row.totalServiceFee / 10000 - row.serviceFee / 10000) * 1000000) / 1000000
      },
      submitForm(formName) {
        const params = new FormData()
        if (!this.dialogType) {
          params.append('depositId', this.teamRow.depositId)
        }
        params.append('tenderId', this.teamRow.tenderId)
        params.append('tenderName', this.teamRow.tenderName)
        params.append('serviceFee', this.teamRow.serviceFee || 0)
        params.append('teamId', this.teamRow.teamId)
        params.append('teamName', this.teamRow.teamName)
        params.append('amount', this.teamRow.amount)
        params.append('datePayStr', formatDate(new Date(this.teamRow.datePay), 'yyyy-MM-dd'))
        params.append('receiveCompany', this.teamRow.receiveCompany)
        params.append('file', this.teamRow.payCertificate)
        // 判断balanceId 银行余额登记 与原页面不同
        if (this.balanceId) {
          params.append('balanceId', this.balanceId)
        }

        if (this.teamRow.tenderId) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.dialogType) {
                addTenderDeposit(params).then(response => {
                  this.addTeam()
                })
              } else {
                updateTenderDeposit(params).then(response => {
                  this.addTeam()
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else {
          this.$message({
            message: '该项目不存在',
            type: 'warning'
          })
        }
      },
      submitMargin(marginName) {
        this.visible = false
        this.$refs[marginName].validate((valid) => {
          if (valid) {
            if (this.marginType) {
              const params = {
                depositId: this.margin.depositId,
                dateChecked: this.margin.date
              }
              updateIsTransfer(params).then(response => {
                this.marginVisible = false
                this.fetchData()
              })
            } else {
              const params = {
                isReturn: 1,
                teamId: this.margin.teamId,
                depositId: this.margin.depositId,
                tenderId: this.margin.tenderId,
                dateReturn: this.margin.date,
                returnPay: this.margin.returnPay,
                amount: this.margin.amount
              }
              updateIsReturn(params).then(response => {
                this.marginVisible = false
                this.fetchData()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          depositId: scope.row.depositId,
          teamId: scope.row.teamId,
          isReturn: scope.row.isReturn,
          amount: scope.row.amount,
          returnPay: scope.row.returnPay,
          isTransfer: scope.row.isTransfer,
          dateChecked: scope.row.dateChecked,
          dateReturn: scope.row.dateReturn,
          datePay: scope.row.datePay,
          isDel: 1
        }
        deleteTenderDeposit(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      addressChange() {
        this.teamRow.provinceId = this.teamRow.addressId[0]
        this.teamRow.cityId = this.teamRow.addressId[1]
        this.teamRow.address = this.pca[86][this.teamRow.addressId[0]] + this.pca[this.teamRow.addressId[0]][this.teamRow.addressId[1]]
      },
      querySearchProject(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.tenderId
        if (queryString) {
          const params = {
            tenderName: queryString
          }
          selectTenderName(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.tenderName
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectProject(item) {
        this.$set(this.teamRow, 'tenderId', item.tenderId)
        this.$set(this.teamRow, 'tenderName', item.tenderName)
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
      },
      getFile(event) {
        this.teamRow.payCertificate = event.target.files[0]
        console.log(this.teamRow)
      },
      openVisible(msg) {
        this.imgVisible = true
        this.imgMsg = msg
      }
    },
    mounted() {
    },
    watch: {
      'outerVisible': {
        handler(newValue, oldValue) {
          this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
          if (this.$refs['teamRow']) {
            this.$refs['teamRow'].resetFields()
          }
        },
        immediate: true
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .dialog-footer {
    text-align: right;
  }

</style>


<style rel="stylesheet/scss" lang="scss">

</style>
